package com.chuangke.quartz.controller;

import java.util.List;

import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.chuangke.common.http.HttpResult;
import com.chuangke.quartz.entity.SysJob;
import com.chuangke.quartz.service.SysJobService;

/**
 * 调度任务信息操作处理
 * 
 */
@RestController
@RequestMapping("/job")
public class SysJobController {

	@Autowired
	private SysJobService jobService;

	/**
	 * 查询定时任务列表
	 */
	@PreAuthorize("hasAuthority('login:action')")
	@GetMapping("/list")
	public HttpResult list(SysJob sysJob) {
		List<SysJob> list = jobService.list(sysJob);
		return HttpResult.ok(list);
	}

	/**
	 * 获取定时任务详细信息
	 */
	@PreAuthorize("hasAuthority('login:action')")
	@GetMapping(value = "/{jobId}")
	public HttpResult getInfo(@PathVariable("jobId") String jobId) {
		return HttpResult.ok(jobService.findById(jobId));
	}

	/**
	 * 新增定时任务
	 */
	@PreAuthorize("hasAuthority('login:action')")
	@PostMapping(value = "/save")
	public HttpResult add(@RequestBody SysJob job) throws SchedulerException {
		jobService.save(job);
		return HttpResult.ok();
	}

	/**
	 * 修改定时任务
	 */
	@PreAuthorize("hasAuthority('login:action')")
	@PostMapping(value = "/update")
	public HttpResult edit(@RequestBody SysJob job) throws SchedulerException {
		jobService.update(job);
		return HttpResult.ok();
	}

	/**
	 * 定时任务状态修改
	 */
	@PreAuthorize("hasAuthority('login:action')")
	@PostMapping("/changeStatus")
	public HttpResult changeStatus(@RequestBody SysJob job) throws SchedulerException {
		SysJob newJob = jobService.findById(job.getId());
		newJob.setStatus(job.getStatus());
		jobService.changeStatus(newJob);
		return HttpResult.ok();
	}

	/**
	 * 定时任务立即执行一次
	 */
	@PreAuthorize("hasAuthority('login:action')")
	@PostMapping("/run")
	public HttpResult run(@RequestBody SysJob job) throws SchedulerException {
		boolean result = jobService.run(job);
		return result ? HttpResult.ok() : HttpResult.error("任务不存在或已过期！");
	}

	/**
	 * 删除定时任务
	 */
	@PreAuthorize("hasAuthority('login:action')")
	@PostMapping("/delete")
	public HttpResult remove(@RequestBody List<String> jobIds) throws SchedulerException {
		jobService.deleteByIds(jobIds);
		return HttpResult.ok();
	}
}
